package com.prothink.threadproject.xiancheng;

import java.util.Arrays;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;

public class LotteryBox implements Runnable {
    // 使用 ConcurrentLinkedQueue 替代 CopyOnWriteArrayList
    private static final Queue<Integer> prizes = new ConcurrentLinkedQueue<>(Arrays.asList(10, 5, 20350, 100, 200, 500, 800, 2, 80, 300, 700));
    private final String boxName;
    private final Random random = new Random();

    public LotteryBox(String boxName) {
        this.boxName = boxName;
    }

    @Override
    public void run() {
        while (!prizes.isEmpty()) {
            try {
                // Simulate the time taken for drawing
                Thread.sleep(1000);

                // Randomly select a prize
                Integer prize = getRandomPrize();

                if (prize != null) {
                    // Remove the prize from the list
                    prizes.remove(prize);

                    // Print the result
                    System.out.println(boxName + " 又产生了一个 " + prize + " 元大奖");
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println(boxName + " 被中断");
            }
        }
    }

    // 从队列中随机选择一个奖项
    private Integer getRandomPrize() {
        Integer[] array = prizes.toArray(new Integer[0]);
        if (array.length == 0) {
            return null;
        }
        int index = random.nextInt(array.length);
        return array[index];
    }

    public static void main(String[] args) {
        // Create and start two lottery boxes
        Thread box1 = new Thread(new LotteryBox("抽奖箱1"));
        Thread box2 = new Thread(new LotteryBox("抽奖箱2"));

        box1.start();
        box2.start();
    }
}
